package ltd.nullpointer.tcp.core.message;

import ltd.nullpointer.tcp.core.constant.TCPEnum;
import org.apache.commons.lang3.ArrayUtils;

import java.io.UnsupportedEncodingException;

/**
 * 云端错误代码
 * 
 * @ClassName: ErrorMessage.java
 * @Description:
 * @author zhangweilin
 * @date 2018年1月21日 上午10:58:47
 *
 */
public class ErrorMessage extends AbstractTCPMessage {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3647295406475213127L;

	/**
	 * 错误响应头
	 */
	public static final byte[] ERR_HEADER_BYTE = new byte[] { (byte) 0xA5, (byte) 0x65, (byte) 0x72, (byte) 0x72, (byte) 0xAA };

	public ErrorMessage() {
		super.setMsgCode(TCPEnum.MsgCode.msgCode63SysErr.getMessageCode()+"");
	}

	public ErrorMessage(Integer errCode, String errMessage) {
		super();
		super.setMsgCode(TCPEnum.MsgCode.msgCode63SysErr.getMessageCode()+"");
		this.errCode = errCode;
		this.errMessage = errMessage;
	}

	public ErrorMessage(Integer errCode) {
		super();
		super.setMsgCode(TCPEnum.MsgCode.msgCode63SysErr.getMessageCode()+"");
		this.errCode = errCode;
	}

	public ErrorMessage(TCPEnum.ErrorCode errorCode) {
		super();
		super.setMsgCode(TCPEnum.MsgCode.msgCode63SysErr.getMessageCode()+"");
		this.errCode = errorCode.getErrCode();
		this.errMessage = errorCode.getName();
	}

	/**
	 * 错误代码
	 */
	private Integer errCode;

	/**
	 * 错误消息,此不生成报文
	 */
	private String errMessage;

	@Override
	public byte[] getHeader() {
		if (ArrayUtils.isEmpty(header)) {
			header = ERR_HEADER_BYTE;
		}
		return header;
	}

	@Override
	public byte[] getPayloadByte() {
		try {
			// ====以下为采用msgCode=063方案
			// String content=StringUtils.leftPad(getMsgCode()+"",3, "0")+errCode;

			String content = "" + errCode;
			System.out.println("content2: " + content);
			byte[] errCodeByte = content.getBytes("UTF-8");
			return errCodeByte;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return super.getPayloadByte();
	}

	public String getErrMessage() {
		return errMessage;
	}

	public void setErrMessage(String errMessage) {
		this.errMessage = errMessage;
	}

	public void setErrCode(Integer errCode) {
		this.errCode = errCode;
		// System.out.println("设置errCode: "+errCode);
		// try {
		// byte[] errCodeByte=(StringUtils.leftPad(getMsgCode()+"",3,
		// "0")+errCode).getBytes("UTF-8");
		// setPayloadByte(errCodeByte);
		// } catch (UnsupportedEncodingException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
	}

	public Integer getErrCode() {
		return errCode;
	}
}
